package com.qiyuesuo.sdk.sample;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;

import org.springframework.stereotype.Service;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.bean.Company;
import com.qiyuesuo.sdk.v2.bean.Contract;
import com.qiyuesuo.sdk.v2.bean.Signatory;
import com.qiyuesuo.sdk.v2.bean.Stamper;
import com.qiyuesuo.sdk.v2.bean.User;
import com.qiyuesuo.sdk.v2.http.StreamFile;
import com.qiyuesuo.sdk.v2.json.JSONUtils;
import com.qiyuesuo.sdk.v2.param.SignParam;
import com.qiyuesuo.sdk.v2.request.CategoryListRequest;
import com.qiyuesuo.sdk.v2.request.CompanyAuthH5PageRequest;
import com.qiyuesuo.sdk.v2.request.CompanyAuthResultRequest;
import com.qiyuesuo.sdk.v2.request.CompanyDetailRequest;
import com.qiyuesuo.sdk.v2.request.ContractDetailRequest;
import com.qiyuesuo.sdk.v2.request.ContractDraftRequest;
import com.qiyuesuo.sdk.v2.request.ContractInvalidRequest;
import com.qiyuesuo.sdk.v2.request.ContractNoticeRequest;
import com.qiyuesuo.sdk.v2.request.ContractPageRequest;
import com.qiyuesuo.sdk.v2.request.ContractSendRequest;
import com.qiyuesuo.sdk.v2.request.ContractSignCompanyRequest;
import com.qiyuesuo.sdk.v2.request.ContractViewPageRequest;
import com.qiyuesuo.sdk.v2.request.DocumentAddByFileRequest;
import com.qiyuesuo.sdk.v2.request.DocumentDownloadRequest;
import com.qiyuesuo.sdk.v2.request.UserAuthPageRequest;
import com.qiyuesuo.sdk.v2.request.UserAuthResultRequest;
import com.qiyuesuo.sdk.v2.response.CategoryListResult;
import com.qiyuesuo.sdk.v2.response.CompanyAuthPageResult;
import com.qiyuesuo.sdk.v2.response.CompanyAuthResult;
import com.qiyuesuo.sdk.v2.response.ContractPageResult;
import com.qiyuesuo.sdk.v2.response.DocumentAddResult;
import com.qiyuesuo.sdk.v2.response.SdkResponse;
import com.qiyuesuo.sdk.v2.response.UserAuthPageResult;
import com.qiyuesuo.sdk.v2.response.UserAuthResult;
import com.qiyuesuo.sdk.v2.utils.IOUtils;

@Service
public class QiyuesuoImpl {
    private String serverUrl = "https://openapi.qiyuesuo.cn";
    private String accessKey = "aS81PVOmMl";
    private String accessSecret = "sVyIhcrA1w9o7rfY3paYBWF7AfxN5m";


	/**
	 *
	 * 功能描述:
	 *
	 * @param: [contractName 合同名, tenantName 接受人名 , signingPeriod 签名时间, userInfo_org_1, userInfo_org_2, userInfo_sup_1, userInfo_sup_2]
	 * @return: com.qiyuesuo.sdk.v2.response.SdkResponse<com.qiyuesuo.sdk.v2.bean.Contract>
	 * @auther: Tangzhiqiang
	 * @date: 2020/3/4 0004 下午 7:22
	 */
    public SdkResponse<Contract> draft(String contractName, String tenantName) {

        try {
            // 初始化sdkClient
            SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);

            // 合同基本参数
            Contract contract = new Contract();
            contract.setSubject(contractName);
            contract.setTenantName("测试222222");
//			contract.setExpireTime(sdf.format(calendar.getTime()));
            contract.setSend(false);

            // 甲方
            Signatory signatory_A = new Signatory();
            signatory_A.setTenantName("测试222222");
            signatory_A.setTenantType("COMPANY");
            signatory_A.setReceiver(new User("唐志强", "18229781528", "MOBILE"));
            signatory_A.setSerialNo(1);

            // 乙方
            Signatory signatory_B = new Signatory();
            signatory_B.setTenantName("部门2222");
            signatory_B.setTenantType("COMPANY");
            signatory_B.setReceiver(new User("唐志强", "18229781528", "MOBILE"));
            signatory_B.setSerialNo(2);

            // 设置签署方
            contract.addSignatory(signatory_A);
            contract.addSignatory(signatory_B);

            // 创建合同
            ContractDraftRequest request = new ContractDraftRequest(contract);
            String response = sdkClient.service(request);
            SdkResponse<Contract> responseObj = JSONUtils.toQysResponse(response, Contract.class);
            // 返回结果
            return responseObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加合同文件
     */
    public SdkResponse<DocumentAddResult> addbyfile(Long contractId, String contractName, String contractPath, String extension) {
        try {
            // 初始化sdkClient
            SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
            // 添加合同文档
            StreamFile sf = new StreamFile(new FileInputStream(contractPath));
            DocumentAddByFileRequest request = new DocumentAddByFileRequest(contractId, sf, extension, contractName);
            String response = sdkClient.service(request);
            SdkResponse<DocumentAddResult> responseObj = JSONUtils.toQysResponse(response, DocumentAddResult.class);
            return responseObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发起合同
     */
    public SdkResponse<Object> sendContract(Long contractId, Long documentId, String orgname, Contract contractData) {
        try {
            // 初始化sdkClient
            SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);

            long actionId_A_1 = contractData.getSignatories().get(0).getActions().get(0).getId();
            long actionId_A_2 = contractData.getSignatories().get(0).getActions().get(1).getId();
            long actionId_B_1 = contractData.getSignatories().get(1).getActions().get(0).getId();
            long actionId_B_2 = contractData.getSignatories().get(1).getActions().get(1).getId();

            /******************** 配置甲方签署位置信息开始 ********************/
            // 1、经办人
            // 配置签名位置
            Stamper stamper_A_1 = new Stamper();
            stamper_A_1.setActionId(actionId_A_1);
            stamper_A_1.setDocumentId(documentId);
            stamper_A_1.setType("PERSONAL");
            stamper_A_1.setKeyword("委托代理人（签字）：");
            stamper_A_1.setKeywordIndex(-2);
            stamper_A_1.setOffsetX(0.0);
            stamper_A_1.setOffsetY(-0.02);

            // 2、签章员
            // 配置时间戳位置
            Stamper stamper_A_2_1 = new Stamper();
            stamper_A_2_1.setActionId(actionId_A_2);
            stamper_A_2_1.setDocumentId(documentId);
            stamper_A_2_1.setType("TIMESTAMP");
            stamper_A_2_1.setKeyword("电 话：");
            stamper_A_2_1.setKeywordIndex(-2);
            stamper_A_2_1.setOffsetX(0.1);
            stamper_A_2_1.setOffsetY(-0.04);
            // 配置公章签署位置
            Stamper stamper_A_2_2 = new Stamper();
            stamper_A_2_2.setActionId(actionId_A_2);
            stamper_A_2_2.setDocumentId(documentId);
            stamper_A_2_2.setType("COMPANY");
            //		stamper_A_2_2.setKeyword("委托代理人（签字）：");
            //		stamper_A_2_2.setKeywordIndex(-2);
            stamper_A_2_2.setKeyword("甲方（盖章）：");
            stamper_A_2_2.setKeywordIndex(-1);
            stamper_A_2_2.setOffsetX(0.0);
            stamper_A_2_2.setOffsetY(-0.14);
            // 配置骑缝章签署位置
            Stamper stamper_A_2_3 = new Stamper();
            stamper_A_2_3.setActionId(actionId_A_2);
            stamper_A_2_3.setDocumentId(documentId);
            stamper_A_2_3.setType("ACROSS_PAGE");
            stamper_A_2_3.setOffsetY(0.3);
            /******************** 配置甲方签署位置信息结束 ********************/

            /******************** 配置乙方签署位置信息开始 ********************/
            // 1、经办人
            // 配置签名位置
            Stamper stamper_B_1 = new Stamper();
            stamper_B_1.setActionId(actionId_B_1);
            stamper_B_1.setDocumentId(documentId);
            stamper_B_1.setType("PERSONAL");
            stamper_B_1.setKeyword("委托代理人（签字）：");
            stamper_B_1.setKeywordIndex(-1);
            stamper_B_1.setOffsetX(0.0);
            stamper_B_1.setOffsetY(-0.02);

            // 2、签章员
            // 配置时间戳位置
            Stamper stamper_B_2_1 = new Stamper();
            stamper_B_2_1.setActionId(actionId_B_2);
            stamper_B_2_1.setDocumentId(documentId);
            stamper_B_2_1.setType("TIMESTAMP");
            stamper_B_2_1.setKeyword("电 话：");
            stamper_B_2_1.setKeywordIndex(-1);
            stamper_B_2_1.setOffsetX(0.1);
            stamper_B_2_1.setOffsetY(-0.04);
            // 配置公章签署位置
            Stamper stamper_B_2_2 = new Stamper();
            stamper_B_2_2.setActionId(actionId_B_2);
            stamper_B_2_2.setDocumentId(documentId);
            stamper_B_2_2.setType("COMPANY");
            //		stamper_B_2_2.setKeyword("委托代理人（签字）：");
            //		stamper_B_2_2.setKeywordIndex(-1);
            stamper_B_2_2.setKeyword("乙方（盖章）：");
            stamper_B_2_2.setKeywordIndex(-1);
            stamper_B_2_2.setOffsetX(0.0);
            stamper_B_2_2.setOffsetY(-0.14);
            // 配置骑缝章签署位置
            Stamper stamper_B_2_3 = new Stamper();
            stamper_B_2_3.setActionId(actionId_B_2);
            stamper_B_2_3.setDocumentId(documentId);
            stamper_B_2_3.setType("ACROSS_PAGE");
            stamper_B_2_3.setOffsetY(0.7);
            /******************** 配置乙方签署位置信息结束 ********************/

            // 添加以上配置
            List<Stamper> stampers = new ArrayList<>();
            stampers.add(stamper_A_1);
            stampers.add(stamper_A_2_1);
            stampers.add(stamper_A_2_2);
            stampers.add(stamper_A_2_3);
            stampers.add(stamper_B_1);
            stampers.add(stamper_B_2_1);
            stampers.add(stamper_B_2_2);
            stampers.add(stamper_B_2_3);
            // 发起合同
            ContractSendRequest request = new ContractSendRequest(contractId, stampers);
            String response = sdkClient.service(request);
            SdkResponse<Object> responseObj = JSONUtils.toQysResponse(response, Object.class);

            return responseObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 合同催签
     */
    public Map sendNotice(Long contractId) {
        Map result = new HashMap();
        String code = "0";
        String message = "";
        try {
            // 初始化sdkClient
            SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
            // 合同催签
            ContractNoticeRequest request = new ContractNoticeRequest(contractId);
            String response = sdkClient.service(request);
            SdkResponse responseObj = JSONUtils.toQysResponse(response);
            if (responseObj.getCode() == 0) {

            } else {
                code = responseObj.getCode().toString();
                message = responseObj.getMessage();
            }
        } catch (Exception e) {
            code = "1";
            message = e.getMessage();
        }
        result.put("code", code);
        result.put("message", message);
        return result;
    }

    /**
     * 合同页面-签署页面
     */
    public String getPageUrl(Long contractId, String phone) {
        String url = "";

        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 页面
        ContractPageRequest request = new ContractPageRequest(contractId, new User(phone, "MOBILE"), "");
        String response = sdkClient.service(request);
        SdkResponse<ContractPageResult> responseObj = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if (responseObj.getCode() == 0) {
            ContractPageResult result = responseObj.getResult();
            url = result.getPageUrl();
        } else {

        }

        return url;
    }

    /**
     * 合同页面-浏览页面
     */
    public String getViewUrl(Long contractId) {
        String url = "";

        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 页面
        ContractViewPageRequest request = new ContractViewPageRequest(contractId);
        String response = sdkClient.service(request);
        SdkResponse<ContractPageResult> responseObj = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if (responseObj.getCode() == 0) {
            ContractPageResult result = responseObj.getResult();
            url = result.getPageUrl();
        } else {

        }

        return url;
    }

    /**
     * 签署公章
     */
    public void companySign(String contractId) {
        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 签署公章
        SignParam param = new SignParam();
        param.setContractId(Long.parseLong(contractId));
        ContractSignCompanyRequest request = new ContractSignCompanyRequest(param);
        String response = sdkClient.service(request);
        SdkResponse<Object> responseObj = JSONUtils.toQysResponse(response, Object.class);
        if (responseObj.getCode() == 0) {

        } else {

        }
    }

    /**
     * 合同撤回（仅针对签署中合同）
     */
    public Map invalid(Long contractId) {
        Map result = new HashMap();
        String code = "0";
        String message = "";
        try {
            // 初始化sdkClient
            SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
            // “签署中”状态下撤回合同
            ContractInvalidRequest request = new ContractInvalidRequest(contractId, "撤回合同");
            String response = sdkClient.service(request);
            SdkResponse responseObj = JSONUtils.toQysResponse(response);
            if (responseObj.getCode() == 0) {

            } else {
                code = responseObj.getCode().toString();
                message = responseObj.getMessage();
            }
        } catch (Exception e) {
            code = "1";
            message = e.getMessage();
        }
        result.put("code", code);
        result.put("message", message);
        return result;
    }

    /**
     * 下载合同文件
     */
    public boolean downloadContract(Long document_id, String downloadPath) {
        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 下载合同文档
        DocumentDownloadRequest request = new DocumentDownloadRequest(document_id);
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(downloadPath);
            sdkClient.download(request, fos);
            IOUtils.safeClose(fos);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 查询公司信息
     */
    public Company getCompanyInfo(String conpanyName) {
        Long id = -1L;

        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 公司信息
        CompanyDetailRequest request = new CompanyDetailRequest(conpanyName);
        String response = sdkClient.service(request);
        SdkResponse<Company> responseObj = JSONUtils.toQysResponse(response, Company.class);
        if (responseObj.getCode() == 0) {
            Company result = responseObj.getResult();
            return result;
        } else {
            return new Company();
        }
    }

    /**
     * 查询业务分类信息
     */
    public void getCategoryList() {
        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 业务分类列表
        CategoryListRequest request = new CategoryListRequest();
        String response = sdkClient.service(request);
        SdkResponse<CategoryListResult> responseObj = JSONUtils.toQysResponse(response, CategoryListResult.class);
        if (responseObj.getCode() == 0) {
            CategoryListResult categoryList = responseObj.getResult();
            System.out.println(categoryList.getTotalCount());
        } else {

        }
    }

    /**
     * 查询合同详情
     */
    
    public Contract getContractDetail(String contractId) {
        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 合同详情
        ContractDetailRequest request = new ContractDetailRequest(Long.parseLong(contractId));
        String response = sdkClient.service(request);
        SdkResponse<Contract> responseObj = JSONUtils.toQysResponse(response, Contract.class);
        if (responseObj.getCode() == 0) {
            Contract contract = responseObj.getResult();
            return contract;
        } else {
            return new Contract();
        }
    }

    /**
     * 获取个人认证链接
     */
    
    public String getPersonalAuth(String userName, String phone) {
        String url = "";

        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 获取个人认证链接
        UserAuthPageRequest request = new UserAuthPageRequest();
        request.setUser(new User(userName, phone, "MOBILE"));
        String response = sdkClient.service(request);
        SdkResponse<UserAuthPageResult> responseObj = JSONUtils.toQysResponse(response, UserAuthPageResult.class);
        if (responseObj.getCode() == 0) {
            url = responseObj.getResult().getAuthUrl();
        } else {

        }

        return url;
    }

    /**
     * 查询个人认证状态
     */
    
    public boolean getPersonalAuthInfo(String phone) {
        boolean result = false;

        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 个人认证查询
        UserAuthResultRequest request = new UserAuthResultRequest(new User(phone, "MOBILE"));
        String response = sdkClient.service(request);
        SdkResponse<UserAuthResult> responseObj = JSONUtils.toQysResponse(response, UserAuthResult.class);
        if (responseObj.getCode() == 0) {
            result = responseObj.getResult().getRealName();
//			logger.info("合同详情查询，合同主题：{}", contract.getSubject());
        } else {
//			logger.info("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }

        return result;
    }

    /**
     * 获取企业认证链接
     */
    
    public String getCompanyAuth(String companyName, String userName, String phone) {
        String url = "";

        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 获取企业认证链接
        User applicant = new User(userName, phone, "MOBILE");
        CompanyAuthH5PageRequest request = new CompanyAuthH5PageRequest(companyName, applicant);
        String response = sdkClient.service(request);
        SdkResponse<CompanyAuthPageResult> pageResultResponse = JSONUtils.toQysResponse(response, CompanyAuthPageResult.class);
        if (pageResultResponse.getCode() == 0) {
            url = pageResultResponse.getResult().getAuthUrl();
//			logger.info("合同详情查询，合同主题：{}", contract.getSubject());
        } else {
//			logger.info("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }

        return url;
    }

    /**
     * 查询企业认证状态
     */
    
    public int getCompanyAuthInfo(String companyName) {
        int result = 0;

        // 初始化sdkClient
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 企业认证查询
        CompanyAuthResultRequest request = new CompanyAuthResultRequest();
        request.setCompanyName(companyName);
        String response = sdkClient.service(request);
        SdkResponse<CompanyAuthResult> resultResponse = JSONUtils.toQysResponse(response, CompanyAuthResult.class);
        if (resultResponse.getCode() == 0) {
            result = resultResponse.getResult().getStatus();
        } else {

        }

        return result;
    }
}